package com.liveinstars.im.domain.manager.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liveinstars.api.im.query.ChatServerQuery;
import com.liveinstars.im.domain.dao.mapper.ChatServerMapper;
import com.liveinstars.im.domain.dao.model.ChatServer;
import com.liveinstars.im.domain.manager.ChatServerManager;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.exception.DatabaseException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 聊天服务器 服务实现类
 * </p>
 *
 * @author 8btc
 * @since 2020-03-31
 */
@Service
public class ChatServerManagerImpl extends ServiceImpl<ChatServerMapper, ChatServer> implements ChatServerManager {

    private Logger logger = LoggerFactory.getLogger(ChatServerManagerImpl.class);

    @Override
    public List<ChatServer> listByQuery(ChatServerQuery query) {
        try {
            QueryWrapper<ChatServer> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(query.getIp())) {
                queryWrapper.eq("ip", query.getIp());
            }
            if (StringUtils.isNotEmpty(query.getName())) {
                queryWrapper.eq("name", query.getName());
            }
            if (query.getOnline() != null) {
                queryWrapper.eq("online", query.getOnline());
            }
            if (StringUtils.isNotEmpty(query.getPort())) {
                queryWrapper.eq("port", query.getPort());
            }
            List<ChatServer> list = this.list(queryWrapper);
            return list;
        } catch (Exception e) {
            logger.error("listByQuery params:{} errorMsg:{}",
                    "query="+ JSON.toJSONString(query), e.getMessage(), e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public void add(ChatServer chatServer) {
        try {
            this.save(chatServer);
        } catch (Exception e) {
            logger.error("add params:{} errorMsg:{}",
                    "chatServer="+ JSON.toJSONString(chatServer), e.getMessage(), e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }
}
